﻿#include "loginWindow.h"
#include <QTimer>
//#include "loginB"
LoginWindow::LoginWindow(database &db, QWidget *parent) : QWidget(parent), db(db)
{
    setWindowTitle("用户登录");
    setFixedSize(400, 400);

    // 设置渐变背景
    this->setStyleSheet(R"(
        QWidget {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 #e0eafc, stop:1 #cfdef3);
        }
    )");

    // 卡片容器
    QWidget *card = new QWidget(this);
    card->setObjectName("loginCard");
    card->setFixedSize(360, 340);
    card->move(20, 30);
    card->setStyleSheet(R"(
        QWidget#loginCard {
            background: #fff;
            border-radius: 18px;
            box-shadow: 0 8px 32px 0 rgba(31,38,135,0.18);
            border: 1.5px solid #e3e3e3;
        }
    )");

    QVBoxLayout *mainLayout = new QVBoxLayout(card);
    mainLayout->setSpacing(18);
    mainLayout->setContentsMargins(28, 28, 28, 28);

    // logo
    QLabel *logoLabel = new QLabel(card);
    logoLabel->setAlignment(Qt::AlignCenter);
    logoLabel->setPixmap(QPixmap(":/img/img/clm.png").scaled(60, 60, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    mainLayout->addWidget(logoLabel);

    // 标题
    QLabel *titleLabel = new QLabel("用户登录", card);
    titleLabel->setStyleSheet("font-size: 20pt; font-weight: bold; color: #409EFF;");
    titleLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(titleLabel);

    // 表单布局
    QFormLayout *formLayout = new QFormLayout();
    formLayout->setSpacing(12);

    phoneEdit = new QLineEdit(card);
    passwordEdit = new QLineEdit(card);
    QString inputStyle = "QLineEdit { font-size: 13pt; padding: 10px; border: 1.5px solid #bfcbd9; border-radius: 8px; background: #f7fafd; } QLineEdit:focus { border-color: #409EFF; }";
    phoneEdit->setStyleSheet(inputStyle);
    passwordEdit->setStyleSheet(inputStyle);
    phoneEdit->setMinimumHeight(38);
    passwordEdit->setMinimumHeight(38);
    passwordEdit->setEchoMode(QLineEdit::Password);
    QLabel *phoneLabel = new QLabel("账号:", card);
    QLabel *passwordLabel = new QLabel("密码:", card);
    phoneLabel->setStyleSheet("font-size: 13pt; color: #666;");
    passwordLabel->setStyleSheet("font-size: 13pt; color: #666;");
    formLayout->addRow(phoneLabel, phoneEdit);
    formLayout->addRow(passwordLabel, passwordEdit);
    mainLayout->addLayout(formLayout);

    // 按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(18);
    loginButton = new QPushButton("登录", card);
    loginButton->setObjectName("loginButton");
    registerButton = new QPushButton("注册", card);
    registerButton->setObjectName("registerButton");
    cancelButton = new QPushButton("取消", card);
    loginButton->setMinimumHeight(38);
    registerButton->setMinimumHeight(38);
    cancelButton->setMinimumHeight(38);
    buttonLayout->addWidget(loginButton);
    buttonLayout->addWidget(registerButton);
    buttonLayout->addWidget(cancelButton);
    mainLayout->addLayout(buttonLayout);

    // 按钮样式
    loginButton->setStyleSheet("QPushButton { background: #409EFF; color: #fff; border-radius: 8px; font-size: 13pt; font-weight: bold; } QPushButton:hover { background: #66B1FF; }");
    registerButton->setStyleSheet("QPushButton { background: #67C23A; color: #fff; border-radius: 8px; font-size: 13pt; font-weight: bold; } QPushButton:hover { background: #85CE61; }");
    cancelButton->setStyleSheet("QPushButton { background: #888; color: #fff; border-radius: 8px; font-size: 13pt; font-weight: bold; } QPushButton:hover { background: #aaa; }");

    // 连接信号和槽
    connect(loginButton, &QPushButton::clicked, this, &LoginWindow::onLoginClicked);
    connect(cancelButton, &QPushButton::clicked, this, [this](){this->close();});
    connect(registerButton, &QPushButton::clicked, this, &LoginWindow::onRegisterClicked);
}

void LoginWindow::onLoginClicked()
{
    QString phone = phoneEdit->text().trimmed();
    QString password = passwordEdit->text();

    if (phone.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "账号和密码不能为空!");
        return;
    }

    // 查询账号是否存在
    QString sql = QString("SELECT phone, password, identity, phone_id FROM phone WHERE phone = '%1'").arg(phone);
    query = db.exec(sql);

    if (query.next()) {
        // 账号存在，验证密码
        QString dbPassword = query.value(1).toString();

        if (password == dbPassword) {
            // 密码正确，登录成功
            int userIdentity = query.value(2).toInt();
            int phoneId = query.value(3).toInt();
            qDebug()<<"登录成功";

            // 发射登录成功信号
            emit loginSuccess(true, phone, userIdentity, phoneId);

            // 先隐藏窗口，在下一个事件循环中关闭它
            hide();
            QTimer::singleShot(0, this, &QWidget::close);
        } else {
            // 密码错误
            QMessageBox::warning(this, "登录失败", "密码错误!");
        }
    } else {
        // 账号不存在
        QMessageBox::warning(this, "登录失败", "账号不存在!");
    }
}

//注册功能
void LoginWindow::onRegisterClicked()
{
    // 创建一个新的独立窗口作为注册窗口
    regiest = new QWidget(nullptr);
    regiest->setWindowTitle("用户注册");
    regiest->setFixedSize(800, 450);

    // 设置窗口标志，确保它显示在最上层
    regiest->setWindowFlags(Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint);

    // 设置窗口位置居中
    if (this->parentWidget()) {
        regiest->move(this->parentWidget()->window()->frameGeometry().center() - regiest->rect().center());
    } else {
        regiest->move(this->window()->frameGeometry().center() - regiest->rect().center());
    }

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(regiest);
    mainLayout->setSpacing(15);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    // 创建标题
    QLabel *titleLabel = new QLabel("用户注册", regiest);
    titleLabel->setStyleSheet("font-size: 18pt; font-weight: bold;");
    titleLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(titleLabel);

    // 创建表单布局
    QFormLayout *formLayout = new QFormLayout();
    formLayout->setSpacing(10);

    // 创建输入框并增大尺寸
    nameEdit = new QLineEdit(regiest);
    phoneEdit = new QLineEdit(regiest);
    passwordEdit = new QLineEdit(regiest);
    confirmPasswordEdit = new QLineEdit(regiest);

    // 设置样式和大小
    QString inputStyle = "QLineEdit { font-size: 12pt; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }";
    nameEdit->setStyleSheet(inputStyle);
    phoneEdit->setStyleSheet(inputStyle);
    passwordEdit->setStyleSheet(inputStyle);
    confirmPasswordEdit->setStyleSheet(inputStyle);

    nameEdit->setMinimumHeight(40);
    phoneEdit->setMinimumHeight(40);
    passwordEdit->setMinimumHeight(40);
    confirmPasswordEdit->setMinimumHeight(40);

    // 密码模式
    passwordEdit->setEchoMode(QLineEdit::Password);
    confirmPasswordEdit->setEchoMode(QLineEdit::Password);

    // 添加到布局
    QLabel *nameLabel = new QLabel("昵称:", regiest);
    QLabel *phoneLabel = new QLabel("账号:", regiest);
    QLabel *passwordLabel = new QLabel("密码:", regiest);
    QLabel *confirmPasswordLabel = new QLabel("确认密码:", regiest);

    nameLabel->setStyleSheet("font-size: 12pt;");
    phoneLabel->setStyleSheet("font-size: 12pt;");
    passwordLabel->setStyleSheet("font-size: 12pt;");
    confirmPasswordLabel->setStyleSheet("font-size: 12pt;");

    formLayout->addRow(nameLabel, nameEdit);
    formLayout->addRow(phoneLabel, phoneEdit);
    formLayout->addRow(passwordLabel, passwordEdit);
    formLayout->addRow(confirmPasswordLabel, confirmPasswordEdit);

    mainLayout->addLayout(formLayout);

    // 创建按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(15);

    // 创建按钮（注意：这里创建新的按钮，不要复用类成员变量）
    QPushButton *registerBtn = new QPushButton("注册", regiest);
    registerBtn->setObjectName("registerButton");

    QPushButton *cancelBtn = new QPushButton("取消", regiest);

    QPushButton *loginBtn = new QPushButton("去登录", regiest);
    loginBtn->setObjectName("loginButton");

    registerBtn->setMinimumHeight(40);
    cancelBtn->setMinimumHeight(40);
    loginBtn->setMinimumHeight(40);

    // 添加按钮到布局
    buttonLayout->addWidget(registerBtn);
    buttonLayout->addWidget(cancelBtn);
    buttonLayout->addWidget(loginBtn);

    mainLayout->addLayout(buttonLayout);

    // 加载样式表
    QFile file(":/style/loginButton.css");
    if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        regiest->setStyleSheet(file.readAll());
        file.close();
    }

    // 连接信号和槽
    connect(registerBtn, &QPushButton::clicked, this, &LoginWindow::Regist);

    // 取消按钮和去登录按钮使用延迟关闭机制
    connect(cancelBtn, &QPushButton::clicked, [this](){
        // 先显示登录窗口
        this->show();
        this->activateWindow();

        // 然后在下一个事件循环中关闭注册窗口
        QTimer::singleShot(0, regiest, [this](){
            if (regiest) {
                regiest->close();
                regiest->deleteLater();
                regiest = nullptr;
            }
        });
    });

    connect(loginBtn, &QPushButton::clicked, [this](){
        // 先显示登录窗口
        this->show();
        this->activateWindow();

        // 然后在下一个事件循环中关闭注册窗口
        QTimer::singleShot(0, regiest, [this](){
            if (regiest) {
                regiest->close();
                regiest->deleteLater();
                regiest = nullptr;
            }
        });
    });

    // 显示注册窗口，但先不隐藏登录窗口
    regiest->show();
    regiest->activateWindow();  // 确保注册窗口获得焦点
    regiest->raise();           // 确保注册窗口在最前面

    // 显示注册窗口后再隐藏登录窗口
    this->hide();
}

//注册逻辑
void LoginWindow::Regist(){
    qDebug() << "279-注册槽函数执行了";

    // 获取输入值
    QString name = nameEdit->text().trimmed();
    QString phone = phoneEdit->text().trimmed();
    QString password = passwordEdit->text();
    QString confirmPassword = confirmPasswordEdit->text();

    // 验证输入
    if (name.isEmpty() || phone.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
        QMessageBox::warning(regiest, "注册失败", "所有字段都不能为空!");
        return;
    }

    // 验证两次密码是否一致
    if (password != confirmPassword) {
        QMessageBox::warning(regiest, "注册失败", "两次输入的密码不一致!");
        return;
    }

    // 查询账号是否存在
    QString checkSql = QString("SELECT phone FROM phone WHERE phone = '%1'").arg(phone);
    query = db.exec(checkSql);

    if (query.next()) {
        // 账号已存在
        QMessageBox::warning(regiest, "注册失败", "该手机号已注册!");
        return;
    }

    // 账号不存在，可以注册
    // 1. 插入到phone表
    QString insertPhoneSql = QString("INSERT INTO phone (phone, password, identity) VALUES ('%1', '%2', 1)")
                            .arg(phone).arg(password);

    if (!db.exec(insertPhoneSql).isActive()) {
        QMessageBox::warning(regiest, "注册失败", "添加用户信息失败，请重试!");
        return;
    }

    // 2. 获取刚插入记录的phone_id
    QString getIdSql = QString("SELECT phone_id FROM phone WHERE phone = '%1'").arg(phone);
    query = db.exec(getIdSql);

    if (!query.next()) {
        QMessageBox::warning(regiest, "注册失败", "获取用户ID失败，请重试!");
        return;
    }

    int phoneId = query.value(0).toInt();

    // 3. 将用户信息插入user表
    QString insertUserSql = QString("INSERT INTO user (phone_id, user_name) VALUES (%1, '%2')")
                           .arg(phoneId).arg(name);

    if (!db.exec(insertUserSql).isActive()) {
        // 如果用户信息插入失败，删除之前插入的phone记录
        QString deletePhoneSql = QString("DELETE FROM phone WHERE phone_id = %1").arg(phoneId);
        db.exec(deletePhoneSql);

        QMessageBox::warning(regiest, "注册失败", "添加用户资料失败，请重试!");
        return;
    }
    // 注册成功
    QMessageBox::information(regiest, "注册成功", "账号注册成功，请登录!");

    // 发送注册成功信号，通知主窗口
    emit registrationSuccess();

    // 然后在下一个事件循环中关闭所有窗口
    QTimer::singleShot(0, [this](){
        if (regiest) {
            regiest->close();
            regiest->deleteLater();
            regiest = nullptr;
        }
        // 关闭登录窗口，而不是显示它
        this->close();
    });
}
